﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Liquid.Collections {
	public class StringBuilderBuffer : BufferBase<char> {
		StringBuilder stringBuilder;

		public StringBuilderBuffer()
			: this(new StringBuilder()) { }
		public StringBuilderBuffer(string str)
			: this(new StringBuilder(str)) { }
		public StringBuilderBuffer(int capacity)
			: this(new StringBuilder(capacity)) { }
		public StringBuilderBuffer(StringBuilder from) {
			this.stringBuilder = from;
		}

		#region IBuffer<char> Members

		public override int Capacity {
			get { return stringBuilder.Capacity; }
			set { stringBuilder.Capacity = value; }
		}

		public override void DeleteNext(int count) {
			stringBuilder.Remove(Position, count);
		}

		public override void DeletePrevious(int count) {
			stringBuilder.Remove(Position - count, count);
			Position -= count;
		}

		public override void Insert(char item) {
			stringBuilder.Insert(Position, item);
			Position++;
		}

		public override void InsertRange(IEnumerable<char> from) {
			var array = from.ToArray();
			stringBuilder.Insert(Position, array);
			Position += array.Length;
		}

		public override int Position { get; set; }

		public override char Previous {
			get { return stringBuilder[Position]; }
		}

		public override char Next {
			get { return stringBuilder[Position + 1]; }
		}

		#endregion

		#region IList<char> Members

		public override int IndexOf(char item) {
			for (int i = 0; i < stringBuilder.Length; i++) {
				if (stringBuilder[i] == item)
					return i;
			}
			return -1;
		}

		public override char this[int index] {
			get { return stringBuilder[index]; }
			set { stringBuilder[index] = value; }
		}

		#endregion

		protected override void CopyBufferCore(int startIndex, char[] array, int arrayIndex, int count) {
			stringBuilder.CopyTo(startIndex, array, arrayIndex, count);
		}

		public override void Clear() {
			stringBuilder.Length = 0;
		}

		public override void CopyTo(char[] array, int arrayIndex) {
			stringBuilder.CopyTo(0, array, arrayIndex, stringBuilder.Length);
		}

		public override int Count {
			get { return stringBuilder.Length; }
		}

		public override IEnumerator<char> GetEnumerator() {
			for (int i = 0; i < stringBuilder.Length; i++) {
				yield return stringBuilder[i];
			}
		}
	}
}
